#!/usr/bin/python
# login oschina
# password need to encrpt by sha1

import sys
import urllib2
import urllib

# secure hashes and message digests
import hashlib

enable_proxy = True

proxy_url = "http://some-proxy.com:8080"
url = "https://www.oschina.net/action/user/hash_login"
timeout = "5"

email = "qingligongzi@163.com"
pwd = "###"

# pwd sha1
encrpt_pwd = hashlib.sha1(pwd).hexdigest()

params = {"email":email,"pwd":encrpt_pwd}
data = urllib.urlencode(params)

headers = {}
headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
headers["Accept-Encoding"] = "gzip, deflate, sdch"
headers["Accept-Language"] = "zh-CN,zh;q=0.8"
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36"

# debug log
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPHandler(debuglevel=1)

# proxy
proxy_handler = urllib2.ProxyHandler({"http":proxy_url})
null_proxy_handler = urllib2.ProxyHandler({})
if enable_proxy:
	opener = urllib2.build_opener(httpsHandler,httpHandler,proxy_handler)
else:
	opener = urllib2.build_opener(httpsHandler,httpHandler,null_proxy_handler)

urllib2.install_opener(opener)

request = urllib2.Request(url, data, headers)

try:
	response = urllib2.urlopen(request,timeout)
except urllib2.HTTPError, e:
	if hasattr(e,"code"):
		print("HTTP ERROR: code:{0},reason:{1}".format(e.code,e.reason))
		sys.exit(0)
except urllib2.URLError,e:
	if hasattr(e,"reason"):
		print("URL ERROR: reason:{0}".format(e.reason))
		sys.exit(0)		
		
result = response.read()

if len(result) == 0:
	print("login success")
else:
	print("login failure:{0}".format(result))	